package com.nep.NEPG.dao;

import com.nep.NEPG.model.SystemUser;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
     private static final String DATA_FILE = "data/users.csv";
     private static final String HEADER = "id,username,password,role";

     public UserDao() {
          initDataFile();
     }

     private void initDataFile() {
          try {
               Path path = Paths.get(DATA_FILE);
               if (!Files.exists(path)) {
                    Files.createDirectories(path.getParent());
                    Files.write(path, (HEADER + System.lineSeparator()).getBytes());
               }
          } catch (IOException e) {
               throw new RuntimeException("初始化数据文件失败", e);
          }
     }

     public List<SystemUser> findAll() {
          List<SystemUser> users = new ArrayList<>();
          try (BufferedReader reader = new BufferedReader(new FileReader(DATA_FILE))) {
               // 跳过标题行
               reader.readLine();

               String line;
               while ((line = reader.readLine()) != null) {
                    String[] parts = line.split(",");
                    if (parts.length == 4) {
                         users.add(new SystemUser(
                                 parts[0].trim(),  // id
                                 parts[1].trim(),  // username
                                 parts[2].trim(),  // password
                                 parts[3].trim()   // role
                         ));
                    }
               }
          } catch (IOException e) {
               throw new RuntimeException("读取用户数据失败", e);
          }
          return users;
     }

     public SystemUser findByUsername(String username) {
          return findAll().stream()
                  .filter(user -> user.getUsername().equals(username))
                  .findFirst()
                  .orElse(null);
     }

     public void save(SystemUser user) {
          List<SystemUser> users = findAll();
          users.removeIf(u -> u.getId().equals(user.getId()));
          users.add(user);
          saveAll(users);
     }

     private void saveAll(List<SystemUser> users) {
          try (BufferedWriter writer = new BufferedWriter(new FileWriter(DATA_FILE))) {
               writer.write(HEADER);
               writer.newLine();

               for (SystemUser user : users) {
                    writer.write(String.join(",",
                            user.getId(),
                            user.getUsername(),
                            user.getPassword(),
                            user.getRole()
                    ));
                    writer.newLine();
               }
          } catch (IOException e) {
               throw new RuntimeException("保存用户数据失败", e);
          }
     }
}